def count_inversions(arr):
    def merge_sort_and_count(arr):
        if len(arr) <= 1:
            return arr, 0
        
        mid = len(arr) // 2
        left, inv_left = merge_sort_and_count(arr[:mid])
        right, inv_right = merge_sort_and_count(arr[mid:])
        merged, inv_merge = merge_and_count(left, right)
        
        total = inv_left + inv_right + inv_merge
        return merged, total
    
    def merge_and_count(left, right):
        result = []
        i = j = 0
        inv_count = 0
        
        while i < len(left) and j < len(right):
            if left[i] <= right[j]:
                result.append(left[i])
                i += 1
            else:
                result.append(right[j])
                j += 1
                inv_count += len(left) - i
        
        result.extend(left[i:])
        result.extend(right[j:])
        return result, inv_count
    
    _, total_inversions = merge_sort_and_count(arr)
    return total_inversions

# 示例用法
arr = [3,1,4,5,2]
print("逆序数:", count_inversions(arr))  # 输出: 5